//
//  SixDivSubViewController.m
//  International_Hospital
//
//  Created by 喵小仲 on 16/7/7.
//  Copyright © 2016年 LiYiLin. All rights reserved.
//


#import "SixDivSubViewController.h"

#import "NetWorkDefine.h"
#import "NetWorkTool.h"

#import "SixDivModel.h"
#import "AnalyseModel.h"

@interface SixDivSubViewController ()<UITextFieldDelegate>

//MARK:显示cell的数据源
@property (nonatomic, strong) NSArray *selectArray;

//MARK:网上获取的数据源
@property (nonatomic, strong) NSArray *dataArray;

//MARK:疾病细分页面中的textfield
@property (nonatomic, weak) UITextField *textField;

//第一次撤销textfield第一响应者
@property (nonatomic, assign) NSInteger index;

@end

@implementation SixDivSubViewController

//MARK:dataArray的setter方法
- (void)setDataArray:(NSArray *)dataArray
{
    _dataArray = dataArray;
}

//MARK:selectArray的setter方法
- (void)setSelectArray:(NSArray *)selectArray
{
    _selectArray = selectArray;
    
    [self.tableView reloadData];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if (!self.index)
    {
        [self.textField becomeFirstResponder];
        
        self.index++;
    }
}

#pragma mark
#pragma mark -- viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
                
            case AFNetworkReachabilityStatusNotReachable:
                
                [SVProgressHUD setMinimumDismissTimeInterval:1.5];
                [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
                [SVProgressHUD showInfoWithStatus:@"网络未连接!"];
                
                break;
                
            default:
                break;
        }
        
    }];
    
    //开启检测
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    [self setup_LeftButtonItem];
    
    [self getTableViewData];
}

#pragma mark
#pragma mark -- 设置nav控制器返回键
- (void)setup_LeftButtonItem
{
    //创建leftButton
    UIButton * left_Button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    //左侧Item白色箭头样式
    [left_Button setImage:[UIImage imageNamed:@"JianTou"] forState:UIControlStateNormal];
    //为Item添加监听点击事件
    [left_Button addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    //将设置好的leftBarButtonItem添加到右侧的Item上
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:left_Button];
}

//MARK:系统提供的方法,如果想跳转到任意的控制器 就重写goBack方法
- (void)goBack
{
    //如果是疾病细分几面,则先撤销输入框的第一响应者
    if ([self.vcTypeString isEqualToString:kAnalysePlaceHolderString])
    {
        [self.textField resignFirstResponder];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark
#pragma mark -- 获取数据的方法
- (void)getTableViewData
{
    //MARK:疾病细分页面 数据获取方法
    if ([self.vcTypeString isEqualToString:kAnalysePlaceHolderString])
    {
        NSString *urlString = kSearchCI3Url;
        NSDictionary *paramDic = @{
                                   @"page_size":@15,
                                   @"page":@1,
                                   @"ci1_id":@1,
                                   @"keyword":@""
                                   };
        
        [[NetWorkTool shareManager] POST_RequestWithUrlString:urlString parmas:paramDic successBloock:^(NSDictionary * responseObject) {
            
            NSArray *array = responseObject[@"data"];
            
            [self changedChineseWithArray:array];
            
        } failureBlock:^(NSError *error) {
            
            NSLog(@"error = %@",error);
            
            [self setupCoverViewWithBlock:^{
                [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
            }];
            
        }];
        
        [self setupTextField];
    }
    //MARK:并发症选择页面 数据获取方法
    else if ([self.vcTypeString isEqualToString:kConcurrentPlaceHolderString])
    {
        self.navigationItem.title = @"并发症";
        
        NSString *urlString = kComplicationListUrl;
        NSDictionary *paramDic = @{@"page":@1,@"page_size":@15,@"ci2_id":@3
                                   };
        
        [[NetWorkTool shareManager] POST_RequestWithUrlString:urlString parmas:paramDic successBloock:^(NSDictionary * responseObject) {
            
            NSArray *dataArray = responseObject[@"data"];
            
            NSMutableArray *mArray = [NSMutableArray array];
            
            for (int i = 0; i < 4; i++)
            {
                [dataArray enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSString *string = obj[@"complication_name"];
                    
                    string = [NSString stringWithFormat:@"%@%d",string,i];
                    
                    SixDivModel *model = [[SixDivModel alloc] init];
                    model.name = string;
                    
                    __block NSInteger index = 0;
                    [self.saveArray enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([obj isEqualToString:string])
                        {
                            index++;
                        }
                    }];
                    
                    if (index)
                    {
                        model.isGet = YES;
                    }
                    else
                    {
                        model.isGet = NO;
                    }
                    
                    [mArray addObject:model];
                }];
            }
            
            self.selectArray = mArray.copy;
            
        } failureBlock:^(NSError *error) {
            
            NSLog(@"error = %@",error);
            
            [self setupCoverViewWithBlock:^{
                [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
            }];
        }];
        
        [self setupRightButton];
    }
    //MARK:治疗方式页面 数据获取方法 (写死的)
    else if ([self.vcTypeString isEqualToString:kCureTypePlaceHolderString])
    {
        self.navigationItem.title = @"治疗方式";
        
        self.selectArray = @[@"手术治疗",@"药物治疗",@"保守治疗"];
    }
}

#pragma mark
#pragma mark -- 中文转英文,并储存
- (void)changedChineseWithArray:(NSArray *)array
{
    NSMutableArray *mArray = [[NSMutableArray alloc] init];
    NSMutableArray *mArrInit = [[NSMutableArray alloc] init];
    
    [array enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSString *string = obj[@"ci3_name"];
        
        if (string.length > 0)
        {
            NSMutableString *mString = [[NSMutableString alloc] initWithString:string];
            
            if (CFStringTransform((__bridge CFMutableStringRef)mString, 0, kCFStringTransformMandarinLatin, NO))
            {
                if (CFStringTransform((__bridge CFMutableStringRef)mString, 0, kCFStringTransformStripDiacritics, NO))
                {
                    AnalyseModel *model = [[AnalyseModel alloc] init];
                    
                    model.pinyin = mString.copy;
                    model.chinese = string;
                    
                    [mArray addObject:model];
                    [mArrInit addObject:model.chinese];
                }
            }
            
        }
    }];
    
    self.dataArray = mArray;
    self.selectArray = mArrInit;
}

#pragma mark
#pragma mark -- 针对并发症页面 设置右边的确定Item
- (void)setupRightButton
{
    UIButton * rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [rightButton setTitle:@"确定" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(didClickIsTureButton:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

#pragma mark
#pragma mark -- 点击确认按钮,储存并发症页面中已订阅的cell信息.block传值
- (void)didClickIsTureButton:(UIButton *)button
{
    if ([self.selectArray[0] isKindOfClass:[SixDivModel class]])
    {
        __block NSString *string = @"";
        [self.selectArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            SixDivModel *model = (SixDivModel *)obj;
            
            //拼接字符串
            if (model.isGet)
            {
                if (string.length != 0)
                {
                    string = [NSString stringWithFormat:@"%@、%@",string,model.name];
                }
                else
                {
                    string = model.name;
                }
            }
        }];
        
        //MARK:block传值给SixDiv_ViewController
        if (self.stringBlock)
        {
            _stringBlock(string);
        }
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark
#pragma mark -- 疾病细分页面 中的textfield
- (void)setupTextField
{
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, kLLAnalyseVcTextFieldWidth, kLLAnalyseVcTextFieldHeigth)];
    self.textField = textField;
    textField.backgroundColor = [UIColor whiteColor];
    textField.layer.cornerRadius = kLLCornerRadius;
    textField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kLLMarginLeft, kLLMarginLeft)];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.keyboardType = UIKeyboardTypeDefault;
    textField.placeholder = @"  请输入关键字";
    self.navigationItem.titleView = textField;
    
    textField.font = kLLFontSize;
    
    //MARK:textfield监听方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:nil];
}

#pragma mark
#pragma mark -- 监听textfield输入
- (void)textFieldValueChanged
{
    NSString *string = [self.textField.text lowercaseString];
    
    NSMutableArray *mArray = [NSMutableArray array];
    
    //遍历网络数据 判断搜索
    [self.dataArray enumerateObjectsUsingBlock:^(AnalyseModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSString *chinese = obj.chinese;
        
        NSString *pinyin = obj.pinyin;
        
        //如果源string存在于搜索string中,那么匹配成功
        NSRange chineseRange = [chinese rangeOfString:string];
        NSRange pinyinRange = [pinyin rangeOfString:string];
        
        if (chineseRange.length > 0)
        {
            [mArray addObject:obj.chinese];
        }
        if (pinyinRange.length > 0)
        {
            if (pinyinRange.location == 0)
            {
                [mArray addObject:obj.chinese];
            }
            else
            {
                NSRange range = {pinyinRange.location - 1,1};
                NSString *temp = [pinyin substringWithRange:range];
                if ([temp isEqualToString:@" "])
                {
                    [mArray addObject:obj.chinese];
                }
            }
        }
    }];
    
    //匹配成功的数据存在数组selectArray中
    self.selectArray = mArray.copy;
}

#pragma mark
#pragma mark -- cell被选择的代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //如果不是并发症页面,则需要点击cell然后直接用block传值
    if (![self.vcTypeString isEqualToString:kConcurrentPlaceHolderString])
    {
        //撤销第一响应者
        if ([self.vcTypeString isEqualToString:kAnalysePlaceHolderString])
        {
            [self.textField resignFirstResponder];
        }
        
        if (self.stringBlock)
        {
            _stringBlock(self.selectArray[indexPath.row]);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    //取消cell选择
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark
#pragma mark -- 滚动的代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.textField resignFirstResponder];
}

#pragma mark
#pragma mark -- 代理方法
//MARK:组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//MARK:行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.selectArray.count;
}

//MARK:cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    //MARK:设置并发症界面的订阅按钮
    if ([self.vcTypeString isEqualToString:kConcurrentPlaceHolderString])
    {
        SixDivModel *model = self.selectArray[indexPath.row];
        
        cell.textLabel.text = model.name;
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kLLConcurrentVcButtonWidth, kLLConcurrentVcButtonHeigth)];
        button.tag = indexPath.row;
        button.selected = model.isGet;
        [button setBackgroundColor:kThemeColor];
        [button setTitle:@"订阅" forState:UIControlStateNormal];
        [button setTitle:@"已订阅" forState:UIControlStateSelected];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        button.layer.cornerRadius = 5;
        
        //订阅按钮的监听方法
        [button addTarget:self action:@selector(didClickButton:) forControlEvents:UIControlEventTouchUpInside];
        
        button.titleLabel.font = kLLFontSize;
        
        cell.accessoryView = button;
    }
    else
    {
        //如果不是并发症界面,则直接设置textLabel
        NSString *name = self.selectArray[indexPath.row];
        
        cell.textLabel.text = name;
    }
    
    //cell类型
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.font = kLLFontSize;
    return cell;
}

//MARK:点击并发症页面的订阅按钮的监听方法
- (void)didClickButton:(UIButton *)button
{
    if (button.selected)
    {
        button.selected = NO;
        
        SixDivModel *model = self.selectArray[button.tag];
        
        model.isGet = NO;
    }
    else
    {
        button.selected = YES;
        
        SixDivModel *model = self.selectArray[button.tag];
        
        model.isGet = YES;
    }
}

#pragma mark
#pragma mark -- 错误遮照 参数:coverBlock
- (void)setupCoverViewWithBlock:(void(^)())coverBlock
{
    //遮罩层
    UIView *coverView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    coverView.backgroundColor = [UIColor lightGrayColor];
    
    coverView.alpha = 0;
    
    [self.view addSubview:coverView];
    
    [UIView animateWithDuration:2 animations:^{
        
        coverView.alpha = 0.5;
        
        if (coverBlock)
        {
            coverBlock();
        }
        
    } completion:^(BOOL finished) {
        
        coverView.alpha = 0;
        //移除
        [SVProgressHUD dismiss];
        
    }];
}

#pragma mark
#pragma mark -- dealloc方法
- (void)dealloc
{
    //    NSLog(@"sixdivsubdealloc");
}

@end
